package com.zhugang.week13.linkedlist;

/**
 * @program algorithms
 * @description: ReverseList
 * @author: chanzhugang
 * @create: 2022/09/09 16:06
 */
public class ReverseList {

    /**
     * 206 反转链表
     * https://leetcode.cn/problems/reverse-linked-list/
     * 时间复杂度：O(n)，n是链表长度
     * 空间复杂度：O(1)
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        // 头插法，数据反过来了，定义结果链表
        // 1-2-3-4-5  ->   5-4-3-2-1
        // 开辟一个新链表， 每遍历一个节点, p.next = newNode; newNode = p
        ListNode newNode = null;
        ListNode p = head;
        while (p != null) {
            ListNode tempNext = p.next;
            // 头插法
            p.next = newNode;
            newNode = p;
            p = tempNext;
        }
        return newNode;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}